<template>
  <div class="role">
    <warning-bar title="注：右上角头像下拉可切换角色" />
	
	<div class="gva-search-box">
	  <el-form :inline="true" :model="searchInfo">
	    <el-form-item label="名称">
	      <el-input v-model="searchInfo.name" placeholder="角色名称" />
	    </el-form-item>
	    <el-form-item>
	      <el-button
	        size="small"
	        type="primary"
	        icon="search"
	        @click="onSubmit"
	      >查询</el-button>
	      <el-button
	        size="small"
	        icon="refresh"
	        @click="onReset"
	      >重置</el-button>
	    </el-form-item>
	  </el-form>
	</div>
	
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="addRole()">新增角色</el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="id"
        style="width: 100%"
      >
        <!-- <el-table-column label="角色ID" min-width="180" prop="id" /> -->
        <el-table-column align="left" label="角色名称" min-width="220" prop="name" />
        <el-table-column align="left" label="角色编码" min-width="220" prop="code" />
        <el-table-column align="left" label="备注" min-width="220" prop="remark" />
        <el-table-column align="left" label="默认菜单(path)" min-width="220" prop="defaultRouter" />
        <el-table-column align="left" label="操作" width="250">
          <template #default="scope">
            <el-button
              icon="setting"
              size="small"
              type="text"
              @click="opdendrawer(scope.row)"
            >设置权限</el-button>
            <el-button
              icon="edit"
              size="small"
              type="text"
              @click="editRole(scope.row)"
            >编辑</el-button>
            <el-button
              icon="delete"
              size="small"
              type="text"
              @click="deleteRoleAction(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
	  <div class="gva-pagination">
	    <el-pagination
	      :current-page="pageNumber"
	      :page-size="pageSize"
	      :page-sizes="[10, 20, 50, 100]"
	      :total="total"
	      layout="total, sizes, prev, pager, next, jumper"
	      @current-change="handleCurrentChange"
	      @size-change="handleSizeChange"
	    />
	  </div>
    </div>
    <!-- 新增角色弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
		<el-form-item label="备注" prop="remark">
		  <el-input v-model="form.remark" autocomplete="off" />
		</el-form-item>
		<el-form-item label="默认菜单(path)" prop="defaultRouter">
		  <el-input disabled v-model="form.defaultRouter" autocomplete="off" />
		</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-if="drawer" v-model="drawer" :with-header="false" size="40%" title="角色配置">
      <el-tabs :before-leave="autoEnter" class="role-box" type="border-card">
        <el-tab-pane label="角色菜单">
          <Menus ref="menus" :row="activeRow" @changeRow="changeRow" />
        </el-tab-pane>
        <!-- <el-tab-pane label="角色api">
          <Apis ref="apis" :row="activeRow" @changeRow="changeRow" />
        </el-tab-pane> -->
        <!-- <el-tab-pane label="资源权限">
          <Datas ref="datas" :authority="tableData" :row="activeRow" @changeRow="changeRow" />
        </el-tab-pane> -->
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  getRoleList,
  deleteRole,
  saveRole
} from '@/api/role'

import Menus from '@/view/superAdmin/role/components/menus.vue'
import warningBar from '@/components/warningBar/warningBar.vue'

import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const mustUint = (rule, value, callback) => {
  if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
    return callback(new Error('请输入正整数'))
  }
  return callback()
}

const pageNumber = ref(1)
const total = ref(0)
const pageSize = ref(20)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  getTableData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageNumber.value = val
  getTableData()
}

const drawer = ref(false)
const dialogType = ref('add')
const activeRow = ref({})

const dialogTitle = ref('新增角色')
const dialogFormVisible = ref(false)
const apiDialogFlag = ref(false)
const copyForm = ref({})

const form = ref({
	id: 0,
    name: '',
    code: '',
    remark: '',
	defaultRouter: ''
})
const rules = ref({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入角色备注', trigger: 'blur' }
  ]
})

// 查询
const getTableData = async() => {
  const table = await getRoleList({ pageNumber: pageNumber.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
  }
}

getTableData()

const changeRow = (key, value) => {
  activeRow.value[key] = value
}
const menus = ref(null)
const apis = ref(null)
const datas = ref(null)
const autoEnter = (activeName, oldActiveName) => {
  const paneArr = [menus, apis, datas]
  if (oldActiveName) {
    if (paneArr[oldActiveName].value.needConfirm) {
      paneArr[oldActiveName].value.enterAndNext()
      paneArr[oldActiveName].value.needConfirm = false
    }
  }
}
const opdendrawer = (row) => {
  drawer.value = true
  activeRow.value = row
}
// 删除角色
const deleteRoleAction = (row) => {
  ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async() => {
      const res = await deleteRole({ id: row.id })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        if (tableData.value.length === 1 && pageNumber.value > 1) {
          pageNumber.value--
        }
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}
// 初始化表单
const roleForm = ref(null)
const initForm = () => {
  if (roleForm.value) {
    roleForm.value.resetFields()
  }
  form.value = {
	id: 0,
    name: '',
    code: '',
    remark: '',
	defaultRouter: ''
  }
}
// 关闭窗口
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
  apiDialogFlag.value = false
}
// 确定弹窗
const enterDialog = () => {
  roleForm.value.validate(async valid => {
    if (valid) {
      switch (dialogType.value) {
        case 'add':
          {
            const res = await saveRole(form.value)
            if (res.code === 0) {
              ElMessage({
                type: 'success',
                message: '保存成功!'
              })
              getTableData()
              closeDialog()
            }
          }
          break
        case 'edit':
          {
            const res = await saveRole(form.value)
            if (res.code === 0) {
              ElMessage({
                type: 'success',
                message: '保存成功!'
              })
              getTableData()
              closeDialog()
            }
          }
          break
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
// 增加角色
const addRole = () => {
  initForm()
  dialogTitle.value = '新增角色'
  dialogType.value = 'add'
  dialogFormVisible.value = true
}
// 编辑角色
const editRole = (row) => {
  dialogTitle.value = '编辑角色'
  dialogType.value = 'edit'
  for (const key in form.value) {
    form.value[key] = row[key]
  }
  dialogFormVisible.value = true
}

</script>

<script>

export default {
  name: 'Role'
}
</script>

<style lang="scss">
.role {
  .el-input-number {
    margin-left: 15px;
    span {
      display: none;
    }
  }
}
.role-box {
  .el-tabs__content {
    height: calc(100vh - 72px);
    overflow: auto;
  }
}
</style>
